package com.epfresh.supplier.activity;

import com.epfresh.api.utils.*;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.epfresh.api.ucrop.UCrop;
import com.epfresh.api.utils.*;

import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.epfresh.supplier.BuildConfig;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.*;
import com.epfresh.api.utils.CipherUtils;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.google.gson.GsonBuilder;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by wzh on 2016/5/6.
 */
public class H5StoreDecorateActivity extends BaseActivity  {
    private WebView webview;
    private ProgressBar pb;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        if (savedInstanceState != null) {
            url = savedInstanceState.getString(Constant.KEY_WEB_URL);
        } else {
            url = getIntent().getStringExtra(Constant.KEY_WEB_URL);
        }
        pb = (ProgressBar) findViewById(R.id.pb);
        webview = (WebView) findViewById(R.id.wv);
        pb.setVisibility(View.VISIBLE);
        webViewSetting();
        url = BuildConfig.H5STORE_BASE + BaseApplication.getInstance().getStoreId();
        //url = "http://180.168.156.212:2135/jdzg-gh-app/1.0.0/index/index.html#/nav/"+ BaseApplication.getInstance().getStoreId();
        if (!TextUtils.isEmpty(url)) {
            Log.e("loadUrl____",url);
            /*http://180.168.156.212:2135/jdzg-gh-app/1.0.0/index/index.html#/nav/*/
            webview.loadUrl(url);
        } else {
            toast("数据错误请重试！");
            finish();
        }
    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(new JsBridge(), "JSBridge");
/*        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);*/
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setUserAgentString(null);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setUseWideViewPort(true);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            private View myView = null;
            private CustomViewCallback myCallback = null;

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                    return;
                }
                ViewGroup parent = (ViewGroup) webview.getParent();
                parent.removeView(webview);
                parent.addView(view);
                myView = view;
                myCallback = callback;
                H5StoreDecorateActivity.this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }

            public void onHideCustomView() {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                if (myView != null) {

                    if (myCallback != null) {
                        myCallback.onCustomViewHidden();
                        myCallback = null;
                    }

                    ViewGroup parent = (ViewGroup) myView.getParent();
                    parent.removeView(myView);
                    parent.addView(webview);
                    myView = null;
                }

                final WindowManager.LayoutParams attrs = H5StoreDecorateActivity.this.getWindow().getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                H5StoreDecorateActivity.this.getWindow().setAttributes(attrs);
                H5StoreDecorateActivity.this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString(Constant.KEY_WEB_URL, url);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    @Override
    public void onBackPressed() {
        finish();
    }
    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOCAL_VIDEO :
                    Log.e("local 视频=",""+filePath);
                    saveFirstPicLocal(intent);
                    requestKey();
                    break;
                case REQUEST_CAMERA_VIDEO:
                    Log.e("拍视频",""+filePath);
                    saveFirstPicLocal(intent);
                    requestKey();
                    break;
                //本地相册选中后的回调，下一步去裁剪
                case REQUEST_TAKE_PICTURE_CROP_CODE:
                    Uri uriAblum = intent.getData();
                    onCropPic(uriAblum, photoURL);
                    break;
                //裁剪照片的回调
                case UCrop.REQUEST_CROP:
                    requestKey();
                    break;
                //调用相机拍照后的回调，去裁剪裁剪
                case REQUEST_TAKE_PHOTO_CROP_CODE:
                    onCropPic(photoURL, photoURL);
                    break;
                default:
                    break;
            }
        }
    }
    String firstPic;
    void saveFirstPicLocal(Intent intent){
        Uri uri = intent.getData();
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(this,uri);
        Bitmap b = media.getFrameAtTime();
        filePath = FileUtil.getImgCacheDir() + "/" + "storeD";
        firstPic = filePath + "first";
        File f = new File(firstPic);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            b.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.e("size", b.getByteCount()+"_______________");
            b = null;
            Log.e("____________________", "已经保存");
        } catch (Exception e) {
            e.printStackTrace();
        }
        filePath = UriUtils.getPath(this,uri); // 路径
        Log.e("filePath=",""+filePath);
        photoURL = Uri.fromFile(new File(filePath));
    }
    //拍摄视频
    public static final int REQUEST_CAMERA_VIDEO = 1111;
    //选取本地视频
    public static final int REQUEST_LOCAL_VIDEO = 2222;
    
    //相机剪裁
    public static final int REQUEST_CAMERA_CROP_CODE = 1991;
    //拍照裁剪的Code
    public static final int REQUEST_TAKE_PHOTO_CROP_CODE = 1003;
    //调用系统图库裁剪Code
    public static final int REQUEST_TAKE_PICTURE_CROP_CODE = 1004;

    //拍照后截屏
    public void getPhoto2CameraCrop(Uri uri) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_CROP_CODE);
        } else {
            Intent intent = startTakePhoto(uri);
            this.startActivityForResult(intent, REQUEST_TAKE_PHOTO_CROP_CODE);
        }
    }

    //用来存储照片的URL
    private Uri photoURL;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "storeD";

    //调用系统照相机，对Intent参数进行封装
    protected Intent startTakePhoto(Uri photoURL) {
        this.photoURL = photoURL;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File newFile = new File(filePath);
            Uri contentUri = FileProvider.getUriForFile(this,
                    ApplicationHelper.getInstance().getFileProvider(), newFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            // 授予目录临时共享权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            return intent;
        } else {
            Intent intent = new Intent();
            intent.putExtra("camerasensortype", 2);
            intent.putExtra("autofocus", true);
            intent.putExtra("fullScreen", false);
            intent.putExtra("showActionIcons", false);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURL);//将拍取的照片保存到指定URI
            return intent;
        }
    }
    //获取系统相册后裁剪
    public void getPhoto2AlbumCrop(Uri uri) {
        startActivityForResult(startTakePicture(uri), REQUEST_TAKE_PICTURE_CROP_CODE);
    }

    //调用系统图库,对Intent参数进行封装
    protected Intent startTakePicture(Uri photoURL) {
        this.photoURL = photoURL;
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");//从所有图片中进行选择
        return intent;
    }
    /*openVideoLibrary 本地视频 takeVideo 选择视频 upload 上传 takePhoto 拍照 openAlbum 相册 loginData 登录信息 deviceInfo 设备信息 appCallBack 返回* */
    private Handler mHandler = new Handler();
    String h5Key = "";
    public class JsBridge {
        @JavascriptInterface
        public void callHandler(String functionName, String value, final String param3) {
            Log.e("functionName:", functionName + "_____________________");
            h5Key = param3;

            if ("openVideoLibrary".equals(functionName)) {
                toast("选择-本地视频");
                Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */ //intent.setType("image/*");  intent.setType("audio/*"); //选择音频
                intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）  intent.setType("video/*;image/*");//同时选择视频和图片  /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);/* 取得相片后返回本画面 */
                startActivityForResult(intent, REQUEST_LOCAL_VIDEO);
            }
            if ("takeVideo".equals(functionName)) {
                toast("拍照-视频");
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);// 创建一个请求视频的意图
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);// 设置视频的质量，值为0-1，
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 300);// 设置视频的录制长度，s为单位
                intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 200 * 1024 * 1024L);// 设置视频文件大小，字节为单位
                startActivityForResult(intent, REQUEST_CAMERA_VIDEO);
            }
            filePath += "_" + getAppApplication().getUser().getAccountId();
            photoURL = Uri.fromFile(new File(filePath));
            if ("openAlbum".equals(functionName)) {
                getPhoto2AlbumCrop(photoURL);
            }
            if ("takePhoto".equals(functionName)) {
                getPhoto2CameraCrop(Uri.fromFile(new File(filePath)));
            }

            if ("upload".equals(functionName)) {
                uploadFlag = param3;
            }
            if ("loginData".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("clientIdentifierCode", getAppApplication().getClientIdentifierCode());
                map.put("token", getAppApplication().getUser().getAccess_token());
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("deviceInfo".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("os", "android");
                map.put("osVersion", Build.VERSION.RELEASE);
                map.put("model", Build.MODEL);
                map.put("net",IntenetUtil.getNetworkState(getBaseContext()));
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("getStoreInfo".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("storeType", BaseApplication.getInstance().getMerchant().getStoreCategoryType());
                map.put("storeName", BaseApplication.getInstance().getStoreName());
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }

            if ("appCallBack".equals(functionName)) {
                finish();
            }
        }
    }

    @TargetApi(10)
    void evaluateJs(final String value) {
        Log.e("javascript",value.toString());
        final int version = Build.VERSION.SDK_INT;// 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        if (version < 19) {
            webview.loadUrl(value);
        } else {
            webview.evaluateJavascript(value, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
    }

    public void requestKey() {
        RequestEntitySupply<Map<String, Object>> entity = new RequestEntitySupply<>();
        Map<String, Object> map = new HashMap<>();
        entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_file_token_upload);
        map.put("isPrivate", false);
        entity.setParameters(map);
        request(entity, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_file_token_upload, onRequestListener);
    }




    OnRequestListener<String> onRequestListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;
//            return new Gson().fromJson(responseStr, String.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {
            showProgressView();
        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            showMainView();
            String orderResponse = response.getResponseElement();

            Log.e("key_", orderResponse + "___________");
            upload(filePath.toString(),orderResponse);
        }
    };
    protected void upload(final String path, String token) {
        File file = new File(path);
        if(firstPic == null) {
            try {
                String files = FileUtil.encodeBase64FileByNoWrap(path);

                evaluateJs("JSBridgeCallback('" + h5Key + "'" + ",'" + files + "')");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                String files = FileUtil.encodeBase64FileByNoWrap(firstPic);

                evaluateJs("JSBridgeCallback('" + h5Key + "'" + ",'" + files + "')");
            } catch (Exception e) {
                e.printStackTrace();
            }
            firstPic = null;
        }

        String accountId = ApplicationHelper.getInstance().getUser().getAccountId();
        UploadManager uploadManager = BaseApplication.getInstance().getUploadManager();
        UpCompletionHandler upCompletionHandler = new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info,final JSONObject response) {
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    //showImage();
                    Log.i("qiniu", "Upload Success");
                } else {
                    //showFail();
                    Log.i("qiniu", "Upload Fail");
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                }
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + uploadFlag + "'" + ",'" + response + "')");
                    }
                });
            }
        };

        String name;
        if(firstPic!=null){
            name =  CipherUtils.generateFileName(accountId, "jpg");
        }else{
            name =  CipherUtils.generateFileName(accountId, "mp4");
        }
        Log.e("name___","name "+name);
        uploadManager.put(file, name, token, upCompletionHandler, new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    public void progress(String key, double percent) {
                        Log.i("qiniu", key + ": " + percent);

                    }
                }, new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return false;/////////////////
            }
        }));
    }
    String uploadFlag;
    private int resultWidth = 512;
    private int resultHeight = 512;
    private int ratioX = 1;
    private int ratioY = 1;
    public void onCropPic(Uri source, Uri destination) {
        UCrop uCrop = UCrop.of(source, destination);
        uCrop.withAspectRatio(ratioX, ratioY);
        uCrop.withMaxResultSize(resultWidth, resultHeight);
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setCompressionQuality(100);
//        options.setMaxBitmapSize(512*512);
        options.setHideBottomControls(true);
        uCrop.withOptions(options);
        uCrop.start(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CAMERA_CROP_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = startTakePhoto(photoURL);
                    startActivityForResult(intent, REQUEST_TAKE_PHOTO_CROP_CODE);
                } else {
                    T.toast("相机获取权限失败");
                }
                return;
            }
        }
    }
}
